package com.xbh.realtime.tio.websocket;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.redis.Redis;
import org.tio.server.ServerGroupContext;
import org.tio.websocket.server.WsServerStarter;
import redis.clients.jedis.Jedis;

import java.io.IOException;

/**
 * @WebSocketStarter: websocket的启动器
 * @author: ZBoHang
 * @time: 2021/8/11 10:16
 */
public class WebSocketStarter implements IPlugin {

    private WebSocketStarter appStarter = null;
    private WsServerStarter wsServerStarter = null;
    private ServerGroupContext serverGroupContext = null;

    public WebSocketStarter(){

    }

    public WebSocketStarter(int port, MyWSMsgHandler myWSMsgHandler) throws IOException {
        wsServerStarter = new WsServerStarter(port, myWSMsgHandler);
        serverGroupContext = wsServerStarter.getServerGroupContext();
        serverGroupContext.setName(MyWSConfig.serverName);
        //设置连接的监听
        serverGroupContext.setServerAioListener(MyWSAioListener.me);

        serverGroupContext.setStopped(false);

        //设置心跳超时时间
        serverGroupContext.setHeartbeatTimeout(MyWSConfig.HEARTBEAT_TIMEOUT);
    }

    @Override
    public boolean start() {

        try {
            appStarter = getWebSocketStart(MyWSMsgHandler.me);
            if (appStarter == null) {
                return false;
            }
            //启动 启动器
            appStarter.wsServerStarter.start();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 使用 端口和 消息处理器 创建 ws启动器

     * @param myWSMsgHandler
     * @return: com.xbh.realtime.tio.websocket.WebSocketStarter
     * @author: ZBoHang
     * @time: 2021/8/11 11:40
     */
    private WebSocketStarter getWebSocketStart(MyWSMsgHandler myWSMsgHandler) throws IOException {

        Integer websocketsPort = Integer.valueOf(PropKit.get("websocketsPort"));
        if (websocketsPort != 0) {
            appStarter = new WebSocketStarter(websocketsPort, myWSMsgHandler);
        }
        return appStarter;
    }

    @Override
    public boolean stop() {
        return appStarter.stop();
    }

}
